import random

import re
from django import http
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.utils.response_code import RET
from meiduo_mall.libs.captcha.captcha import captcha

# 图片验证码
from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils import constants


class ImageCode(View):
    def get(self, request, uuid):
        _, text, image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, constants.REDIS_IMAGE_CODE_EXPIRES, text)
        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpg')


# 短信验证码
class SMSCodeView(View):
    def get(self, reqeust, mobile):

        # 接收参数
        image_code_client = reqeust.GET.get('image_code')
        uuid = reqeust.GET.get('image_code_id')

        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RET.NECESSARYPARAMERR, 'errmsg': '缺少必传参数'})

        if not re.match(r'1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': RET.MOBILEERR, 'errmsg': '手机格式错误'})

        redis_conn = get_redis_connection('code')
        pipeline = redis_conn.pipeline()
        redis_cli_code = redis_conn.get('img_%s' % uuid)
        redis_cli_code = redis_cli_code.decode()
        if image_code_client.upper() != redis_cli_code.upper():

            return http.JsonResponse({'code': RET.DATAERR, 'errmsg': '图形验证码错误'})
        if not redis_cli_code:
            return http.JsonResponse({'code': RET.DATAERR, 'errmsg': '图片验证码已过期'})

        # 以下制作短信验证码
        sms_code = '%06d' % random.randint(0, constants.SMS_CODE_EXPIRES)
        print("短信验证码为：", sms_code)

        # 通过celery发送短信 为了防止网络堵塞等耗时操作导致短信验证码不能正常倒计时，就像一个对队列
        from celery_tasks.sms.tasks import send_message    # 等待调试
        send_message.delay(mobile, sms_code)

        pipeline.set("sms_code_%s" % mobile, sms_code, constants.REDIS_SMS_CODE_EXPIRES)  # 将短信验证码存入redis留作判断是否正确
        redis_cli_flag = redis_conn.get("redis_cli_flag%s" % mobile)  # 将手机号码打上标记，防止频繁发送短信验证码
        if redis_cli_flag:
            return http.JsonResponse({"code": '401', "errmsg": "请勿频繁发送短信"})
            # # 3,1 设置标记,防止1分钟之内, 短信多次发送
        # redis_conn.set("send_flag_%s" % mobile, 1, 60)
        pipeline.set("redis_cli_flag%s" % mobile, 1, constants.REDIS_MOBILE_SMS_CODE_EXPIRES)
        pipeline.execute()  # 最后通过pipeline管道提交数据的redis
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功'})

# Create your views here.
